#region Usings

using System;
using System.Data.Services.Client;
using System.Linq;
using KanbanBoard.Client.Model.Query;

#endregion

namespace KanbanBoard.Client.Model {
    public class TaskBoardQueryService : ITaskBoardQueryService {
        public void GetTaskBoard(Action<TaskBoard> callback) {
            var readModel = new ReadModel(new Uri("http://localhost:51004/Server/Query/TaskBoardQueryService.svc/"));
            var query = readModel.TaskBoards
                .Expand("Columns/Tasks/Column/TaskBoard")
                .Expand("Columns/Tasks/Priority");
            query.BeginExecute(OnGetTaskBoardComplete, new GetTaskBoardState(query, callback));
        }

        private static void OnGetTaskBoardComplete(IAsyncResult ar) {
            var state = (GetTaskBoardState) ar.AsyncState;
            var taskBoard = state.Query.EndExecute(ar).Single();
            state.Callback(taskBoard);
        }

        private class GetTaskBoardState {
            public DataServiceQuery<TaskBoard> Query { get; private set; }
            public Action<TaskBoard> Callback { get; private set; }

            public GetTaskBoardState(DataServiceQuery<TaskBoard> query, Action<TaskBoard> callback) {
                Query = query;
                Callback = callback;
            }
        }
    }
}